package cn.virens.web.components.websocket;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.date.DateUtil;

public class WebSocketHandler extends AbstractWebSocketHandler implements WebSocketPool {
	private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);
	private static final Map<String, WebSocketSession> pool = new ConcurrentHashMap<>();

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		SimplePrincipal principal = (SimplePrincipal) session.getPrincipal();
		logger.debug("连接成功:" + session.getRemoteAddress());
		logger.debug("连接用户:" + principal.toString());

		pool.put(SimplePrincipal.getUuid(principal), session);
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		JSONObject payload = JSON.parseObject(message.getPayload());
		logger.debug("收到消息.content:" + payload.getString("content"));

		Map<String, Object> attributes = session.getAttributes();
		if (attributes != null && !attributes.isEmpty()) {
			payload.put("avatar", WebSocketUtil.getAvatar(session));
			payload.put("name", WebSocketUtil.getName(session));
			payload.put("uuid", WebSocketUtil.getUuid(session));
			payload.put("createTime", DateUtil.now());
			payload.put("self", true);
		} else {
			payload.put("message", "未登录");
			payload.put("code", "no_login");
		}

		// 将消息回传到用户
		this.sendMessage(session, payload);
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		WebSocketSession socketSession = pool.remove(SimplePrincipal.getUuid(session.getPrincipal()));

		logger.debug("断开用户:" + socketSession.getPrincipal().toString());
		logger.debug("连接关闭:" + socketSession.getRemoteAddress());
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		logger.error("连接异常", exception);
	}

	@Override
	public int sendAll(JSONObject json) {
		int result = 0;

		for (WebSocketSession session : pool.values()) {
			result += sendMessage(session, json);
		}

		return result;
	}

	@Override
	public int sendUser(String uuid, JSONObject json) {
		return sendMessage(pool.get(uuid), json);
	}

	private int sendMessage(WebSocketSession session, JSONObject json) {
		try {
			return WebSocketUtil.sendMessage(session, json);
		} catch (Exception e) {
			logger.error("发送失败：" + e.getMessage());
		}

		return 0;
	}

}